/*
    Coder : Dzlua
    Email : 505544956@qq.com
    Time  : 2017/07/14
*/
#include "decoder/decoder.h"
using namespace dzlua;

#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
using std::cerr;

int main(int argc, char *argv[])
{
    if (argc != 2) {
        cerr << "args err. <filename>" << endl;
        return 1;
    }

    std::string outfile = argv[1];
    outfile += ".pcm";
    std::ofstream ofile(outfile, std::ios::binary | std::ios::out | std::ios::trunc);
    if (!ofile.is_open()) return -1;

    auto dc = av::Decoder::NewInterface();

    bool bok = dc->Init();
    if (!bok) {
        cerr << "init err2." << endl;
        return 2;
    }

    bok = dc->Open(argv[1]);
    if (!bok) {
        cerr << "open err3." << endl;
        return 3;
    }

    // only decoder audio
    dc->SetNoUse(true, false, true);

    // set audio info
    {
        auto info = dc->getAudioInfo();
        info->layout = av::eChannelLayout::stereo;
        info->format = av::eSampleFormat::s16;
        info->rate = 44100;
        info->channels = 2;
        dc->setInfo(info.get());
    }

    dc->Run();

    while (true) {
        auto data = dc->pop_audio_data();
        if (!data){
            if (dc->IsDone())
                break;
            continue;
        }
        ofile.write((const char *)data->data, data->size);
    }

    ofile.close();

    return 0;
}
